#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#define NUM 128
#define _NUM 64
  char commend[NUM];
  char* argv[_NUM];
int main()
{
  while(1)
  {
    //打印输入提示符
    printf("[tmt@myhost miniShell]#");
    fflush(stdout);
    //获取用户输入
    char* s = fgets(commend,NUM,stdin);
    if(s==NULL)
    {
      perror("fgets fail\n");
      exit(-1);
    }
    //将回车输入的\n改为\0
    commend[strlen(commend)-1]='\0';
    //将字符串分割，形成argv数组
    char gap[] = " ";
    argv[0] = strtok(commend,gap);
    int i=1;
    while(argv[i]=strtok(NULL,gap))
    {
      i++;
    }
    if(strcmp(argv[0],"cd")==0&&argv[0]!=NULL)
    {
      if(argv[1]!=NULL)
        chdir(argv[1]);
        continue;
      }
    //创建子进程
    pid_t id = fork();
    if(id==-1)
    {
      perror("fork fail\n");
    }
    //子进程进行程序替换
    else if(id==0)
    {
      //进程替换
      execvp(argv[0],argv);
      exit(1);
    }
    //父进程等待
    waitpid(id,NULL,0);

    //i=0;
    //while(argv[i])
    //{
    //  printf("argv[%d]->%s\n",i,argv[i]);
    //  i++;
    //}
   // printf("echo:%s\n",commend);
  }

  return 0;
}
